package com.example.springbootquartz.config;

import com.example.springbootquartz.job.NewJob;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

//@Configuration
public class NewJobQuartzConfig {
//    @Bean("jobDetailFactoryBeanByNewJob")
    public JobDetailFactoryBean jobDetailFactoryBean(){
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        //指定具体的job类
        jobDetailFactoryBean.setJobClass(NewJob.class);
        //指定job的名称
        jobDetailFactoryBean.setName("newJob");
        //指定job的分组
        jobDetailFactoryBean.setGroup("jobs");
        //必须设置为true，如果为false，当没有活动的触发器与之关联时会在调度器中删除该任务
        jobDetailFactoryBean.setDurability(true);
        //指定spring容器的key，如果不设定在job中的jobmap中是获取不到spring容器的(可以自定义key值)
//        jobDetailFactoryBean.setApplicationContextJobDataKey("abc");
        return jobDetailFactoryBean;
    }

    /**
     * 定义触发器
     * @return
     */
//    @Bean("cronTriggerFactoryBeanByNewJob")
    public CronTriggerFactoryBean cronTriggerFactoryBean(@Qualifier("jobDetailFactoryBeanByNewJob") JobDetailFactoryBean jobDetailFactoryBean){
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        //触发的时间频率(30s执行一次)
        cronTriggerFactoryBean.setCronExpression("0/30 * * * * ?");
        return cronTriggerFactoryBean;
    }

    /**
     * 定义调度器
     * @return
     */
//    @Bean("schedulerFactoryBeanByNewJob")
    public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("cronTriggerFactoryBeanByNewJob") CronTriggerFactoryBean cronTriggerFactoryBean){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setTriggers(cronTriggerFactoryBean.getObject());
        return schedulerFactoryBean;
    }
}
